// const avatars = friendList.value
//   .filter((item: any) => item.active)
//   .map((item: any) => item);

// let avatarSrc = await generateGroupAvatar("groupAvatarCanvas", avatars, 200);
// console.log("生成的群头像路径：", avatarSrc);
// return;

// 加载图片的辅助函数
const loadImage = (src: string): Promise<string> => {
  return new Promise((resolve, reject) => {
    uni.getImageInfo({
      src,
      success: (res) => resolve(res.path),
      fail: (err) => reject(err),
    });
  });
};

// 计算头像位置
const calculatePositions = (count: number, canvasSize: number) => {
  const positions: { x: number; y: number }[] = [];
  const gridSize = Math.ceil(Math.sqrt(count));
  const spacing = canvasSize / gridSize;

  for (let i = 0; i < count; i++) {
    const row = Math.floor(i / gridSize);
    const col = i % gridSize;
    positions.push({
      x: col * spacing + spacing / 4,
      y: row * spacing + spacing / 4,
    });
  }
  return positions;
};

// 生成群头像
export const generateGroupAvatar = async (
  canvasId: string,
  friendList: { picture: string }[],
  canvasSize = 200
): Promise<string | null> => {
  return new Promise(async (resolve, reject) => {
    try {
      const ctx = uni.createCanvasContext(canvasId);
      ctx.clearRect(0, 0, canvasSize, canvasSize);

      const avatars = friendList.slice(0, 9); // 最多取 9 个头像
      const positions = calculatePositions(avatars.length, canvasSize);
      const radius = canvasSize / 10; // 每个头像半径

      for (let i = 0; i < avatars.length; i++) {
        const imgPath = await loadImage(avatars[i].picture);
        const { x, y } = positions[i];

        ctx.save();
        ctx.beginPath();
        ctx.arc(x + radius, y + radius, radius, 0, Math.PI * 2);
        ctx.clip(); // 设置圆形裁剪区域
        ctx.drawImage(imgPath, x, y, radius * 2, radius * 2);
        ctx.restore();
      }

      ctx.draw(false, () => {
        uni.canvasToTempFilePath({
          canvasId,
          success: (res) => {
            resolve(res.tempFilePath); // 返回生成的图片路径
          },
          fail: (err) => {
            reject(`生成群头像失败：${err}`);
          },
        });
      });
    } catch (error) {
      reject(`生成群头像过程中出错：${error}`);
    }
  });
};
